<?php

namespace App\Http\Controllers\Admin;
use App\Http\Requests;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Role;
use App\Http\Requests\Admin\AdminUser\CreateRequest;
use App\Http\Requests\Admin\AdminUser\UpdateRequest;
use Illuminate\Support\Facades\DB;
use Style,CustomPassword;

class AdminUserController extends CommonController{
    /**
     * 构造函数
     * AdminUserController constructor.
     */
    public function __construct(){
        $this->middleware('checkPermission:AdminUser|AdminUser-index', ['only' => ['index']]);
        $this->middleware('checkPermission:AdminUser|AdminUser-create', ['only' => ['create', 'store']]);
        $this->middleware('checkPermission:AdminUser|AdminUser-edit', ['only' => ['edit', 'update']]);
        $this->middleware('checkPermission:AdminUser|AdminUser-destroy', ['only' => ['destroy']]);
    }
    /**
     * 用户列表
     * @return mixed
     */
    public function index(){
        $users = AdminUser::paginate(10);
        $userRoleArr = array();
        if(!empty($users)){
            foreach ($users as $k => $v) {
                $userRoleArr[$k] = $v;
                $userRoleArr[$k]['roles'] = $v->roles()->get();
            }
        }
        return Style::view('admin.rbac.admin_users.index', compact('users', 'userRoleArr'));
    }

    /**
     * 添加用户
     * @return mixed
     */
    public function create(){
       $roles = Role::all();
       return Style::view('admin.rbac.admin_users.create', compact('roles'));
    }

    /**
     * 添加用户提交
     * @param CreateRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(CreateRequest $request){
        $input = $request->all();
        $input['password'] = CustomPassword::make($request->input('password'));
        $input['remember_token'] = $request->input('_token');
        $result = AdminUser::create($input);
        if ($result) {
            //给新用户添加角色----------------------------------------------------------------------
            $role_id = array_filter(array_unique($request->input('role_id.*')));
            if (count($role_id) > 0) {
                $user = AdminUser::where('name', '=', $request->input('name'))->first();
                $admin = Role::whereIn('id', $role_id)->get();
                //关联用户和角色之间的中间表
                foreach ($admin as $v) {
                    $user->attachRole($v); // 参数可以是Role对象，数组或id
                }
            }
            //-------------------------------------------------------------------------------------
            flash('新用户添加成功', 'success');
            return redirect('admin/admin_user');
        } else {
            return back()->with('errors', '新用户添加失败，请稍后重试！');
        }
    }

    /**
     * 编辑用户
     * @param $id
     * @return mixed
     */
    public function edit($id){
        $AdminUser = AdminUser::find($id);
        $admin_roles = AdminUser::find($id)->roles()->get();
        $roles = Role::all();
        return Style::view('admin.rbac.admin_users.edit', compact('AdminUser', 'admin_roles', 'roles'));
    }

    /**
     * 更新用户
     * @param UpdateRequest $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(UpdateRequest $request,$id){
//        $input = $request->except(['_method','role_id','_token','password_confirmation']);
        $input = $request->only(['name','email','is_super','id']);
        if(!empty($request->input('password'))){
            $input['password'] = CustomPassword::make($request->input('password'));
        }
        $result = AdminUser::where('id', $id)->update($input);
        if($result){
            if (!$request->input('is_super')) {
                //删除中间表
                DB::table('role_user')->where('user_id', $id)->delete();
                //添加用户角色
                $role_id = array_filter(array_unique($request->input('role_id.*',[])));
                if (count($role_id) > 0) {
                    $user = AdminUser::where('id', $id)->first();
                    $admin = Role::whereIn('id', $role_id)->get();
                    //关联用户和角色之间的中间表
                    foreach ($admin as $v) {
                        $user->attachRole($v); // 参数可以是Role对象，数组或id
                    }
                }
            }
            flash('更新用户成功', 'success');
            return redirect('admin/admin_user');
        }else {
            return back()->with('errors', '用户信息更新失败，请稍后重试！');
        }
    }

    /**
     * 删除用户
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id){
        $result = AdminUser::where('id', $id)->delete();
        if($result){
            DB::table('role_user')->where('user_id', $id)->delete();
            return response()->json(['status' => 0,'msg' => '用户删除成功！']);
        }else{
            return response()->json(['status' => 1,'msg' => '用户删除失败，请稍后重试！']);
        }
    }
}
